import java.io.*;
import java.net.*;
import java.util.zip.*;

public class Mensagem {
	Socket socket = null;
	PrintWriter writer = null;
	BufferedReader reader = null;
	BufferedReader terminal = null;
	
	final String filePath = "/opt/grupo02/";
	
	public Mensagem()
	{

	}
	
	public Mensagem(Socket s) throws IOException
	{
		this();
		setSocket(s);
	}
	
	public void setSocket(Socket s) throws IOException
	{
		socket = s;
		this.abreStreams();
	}
	
	public void abreStreams() throws IOException
	{
		writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
		reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}
	
	public void fechaSreams() throws IOException
	{
		writer.close();
		reader.close();
	}
	
	public void envia(String texto) throws Exception
	{
		if (writer == null)
			throw new Exception("Socket fechado");
		
		if (texto != null && texto.endsWith("\n"))
			texto.concat("\n");
		
		writer.println(texto);
		writer.flush();
	}
	
	public String recebe() throws Exception
	{
		if (reader == null)
			throw new Exception("Socket fechado");
		
		return reader.readLine();
	}
	
	public String readTerminal()
	{
		String str = "";
		try {
			str = terminal.readLine();
		}
		catch (Exception e) {}
		
		return str;
	}
	
	public Boolean enviaArquivo(String nome) throws Exception
	{
		File transferFile = new File (filePath + nome);
		if (!transferFile.exists())
			return false;
		
		this.envia(nome);
		this.envia(String.valueOf(transferFile.length()));
		
        byte [] bytearray = new byte[(int)transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        os.write(bytearray, 0, bytearray.length);
        os.flush();
        bin.close();
        
        return true;
	}
	
	public void recebeArquivo() throws Exception
	{
		String nome = this.recebe();
		int tamanho;
		try {
			tamanho = Integer.parseInt(this.recebe());
		}
		catch (Exception e) {
			return;
		}
		
		int bytesRead;
		int currentTot = 0;
		byte[] bytearray = new byte[tamanho];
		InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(filePath + nome);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(bytearray, 0, bytearray.length);
        currentTot = bytesRead;
 
        do {
        	bytesRead =
        			is.read(bytearray, currentTot, (bytearray.length-currentTot));
        	if(bytesRead >= 0) currentTot += bytesRead;
        } while(bytesRead > 0);
 
        bos.write(bytearray, 0 , currentTot);
        bos.flush();
        bos.close();
	}
}
